<template>
  <el-container>
    <el-header>
      <div class="left-panel">
        <el-button type="primary" icon="el-icon-plus" @click="addNewArea"></el-button>
      </div>
      <div class="right-panel">
        <div class="right-panel-search">
          <el-input v-model="queryParams.name" placeholder="城市名称" @clear="handleInputSearch" clearable></el-input>
          <el-button type="primary" icon="el-icon-search" @click="handleInputSearch"></el-button>
        </div>
      </div>
    </el-header>
    <el-main class="nopadding">
      <el-row class="area-page" :ref="(el) => (areaPageRef = el)">
        <el-col :span="14">
          <el-table v-loading="showGrouploading" :ref="(el) => (areaTableRef = el)" class="area-table" v-bind="areaTableProps" :data="areaList" row-key="id" :tree-props="{children: 'children', hasChildren: 'hasChildren'}" @row-click="rowClick" @clear="handleInputSearch" :load="loadChildrenArea" :lazy="isLazy" size="large">
			  <el-table-column label="城市名称" prop="name" min-width="160"/>
			  <el-table-column label="城市等级" prop="level" align="center">
				  <template #default="scope">
					  <DictTag :options="city_type" :value="scope.row.level"></DictTag>
				  </template>
			  </el-table-column>
			  <el-table-column label="城市编码" prop="cityCode" />
			  <el-table-column label="经度" prop="lng"/>
			  <el-table-column label="纬度" prop="lat"/>
			  <el-table-column label="操作" width="200" align="center">
				  <template v-slot="scope">
					  <el-button type="primary" text @click.stop="handleAdd(scope.row)" class="button">新增</el-button>
            <el-button type="primary" text @click="handleUpdate(scope.row)" class="button">修改</el-button>
					  <el-button type="primary" text @click="handleDelete(scope.row)" class="button">删除</el-button>
				  </template>
			  </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="10">
          <div class="detail-form-wrap" v-if="formTitle">
            <div class="form-title">{{ formTitle }}</div>
            <el-form style="margin-left: 5px; margin-right: 20px" ref="form" :model="form" :rules="rules" label-width="100px">
              <el-form-item label="城市名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入城市名称" />
              </el-form-item>
              <el-form-item label="等级:" prop="level">
                <el-select v-model="form.level" style="width: 100%">
                  <el-option v-for="option in city_type" :key="option.dictValue" :label="option.dictLabel" :value="option.dictValue"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="编码:" prop="cityCode">
                <el-input v-model="form.cityCode" placeholder="请输入城市编码" />
              </el-form-item>
              <el-form-item v-show="showParentSelect" label="父级" prop="pid" >
                <el-cascader v-model="form.pid" :props="props" style="width: 100%" />
              </el-form-item>
              <el-form-item label="经度:" prop="lng">
              <el-input v-model="form.lng" placeholder="请输入城市编码" />
              </el-form-item>
              <el-form-item label="纬度:" prop="lat">
                <el-input v-model="form.lat" placeholder="请输入城市编码" />
              </el-form-item>
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="请输入备注" />
              </el-form-item>
            </el-form>
            <div style="bottom: 0; float: right; top: 0; margin-right: 2%; margin-top: 20px; position: relative">
              <el-button type="primary" :loading="submitLoading" @click="submitForm">确 定</el-button>
              <el-button type="warning" @click="cancelForm">取 消</el-button>
            </div>
          </div>
          <div v-else>
            <el-empty description="请先选择左侧城市后操作" :image-size="100" style="margin-top: 200px"></el-empty>
          </div>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>

<script>
export default {
  name: "systemArea",
  mounted() {
    this.init()
  },
  data() {
    return {
      showGrouploading: true,
      isLazy: true,
      areaTableMaxHeight: "",
      areaPageRef: null,
      areaTableRef: null,
      queryParams: {
      },
      areaList: [],
      formTitle: "",
      resetData: {},
      // 提交按钮加载
	  submitLoading:false,
      form: {
		    id:null
      },
      // 是否显示父级
      showParentSelect:false,
        rules: {
        name:[
          {required: true, message: '城市名称不能为空'}
        ],
        level:[
          {required: true, message: '城市等级不能为空'}
        ],
        cityCode:[
          {required: true, message: '城市编码不能为空'}
        ],
        pid:[
          {required: true, message: '父级不能为空'}
        ]
	  },
		props: {
			lazy: true,
			checkStrictly:true,
			lazyLoad: async (node, resolve) => {
				if (typeof(node.value) != 'undefined'){
					this.queryParams.pid= node.value;
				}
			  let nodes = await this.getAreaListByParam(this.queryParams)
				resolve(nodes)
				this.queryParams={}
			}
		},
	  // 城市等级字典
	  city_type: [],
    }
  },
  computed: {
    areaTableProps() {
      const result = {}
      if (this.areaTableMaxHeight) {
        result.maxHeight = this.areaTableMaxHeight
      }
      return result
    }
  },
  methods: {

    init() {
      this.getAreaList()
      this.setAreaTableMaxHeight()
      this.getDict();
    },
    // 字典获取
    async getDict() {
      this.city_type = await this.Dict.get("sys_city_type");
    },
    // 行点击
    rowClick(row){
      this.handleUpdate(row);
    },
	  // 设置表格最大高度
    setAreaTableMaxHeight() {
      const pageClientHeight = this.areaPageRef.$el.clientHeight
      const areaTableOffsetTop = this.areaTableRef.$el.offsetTop
      this.areaTableMaxHeight = pageClientHeight - areaTableOffsetTop
    },
	  // 查询地址列表
    async getAreaList() {
      this.showGrouploading = true
      const res = await this.$API.system.area.list.get(this.queryParams)
      this.areaList = []
      this.areaList = res.data
      this.showGrouploading = false
    },
	async refresh() {
		const res = await this.$API.system.area.list.get()
		this.areaList = []
		// 重新渲染
		// eslint-disable-next-line vue/valid-next-tick
		await this.$nextTick(() => {
			this.areaList = res.data
			this.showGrouploading = false
		})
	  }  ,
	 // 根据参数获取列表
	 async getAreaListByParam() {
		 const res = await this.$API.system.area.list.get(this.queryParams)
		 // 动态节点
		 const nodes = []
		 if (res.code == 200){
			res.data.map((item) => {
				let area = {
					value: item.id,
					label: item.name,
					leaf: item.level > 2,
				};
				nodes.push(area)
			})
		 }
		return nodes;
	 },
	  // 异步加载
	  async loadChildrenArea(row, treeNode, resolve) {
		  if (row.children.length > 0) return
		  const queryParams = {
			  pid: row.id
		  }
		  const res = await this.$API.system.area.list.get(queryParams)
		  resolve(res.data)
	  },
	// 新建
    addNewArea() {
	  this.showParentSelect =true;
      this.formTitle = "新建行政区表单"
      this.resetData = {
        name: null,
        level: null,
        cityCode: null,
        lng: null,
        lag: null,
      }
      this.form = { ...this.resetData }
    },
	// 表单提交
    submitForm() {
		this.$refs.form.validate(async (valid) => {
			if (valid){
				 this.submitLoading =true;
				 if (this.form.pid instanceof Array){
					 this.form.pid =this.form.pid[this.form.pid.length-1];
				 }
				 let res ={};
				 if (typeof(this.form.id) == 'undefined' || this.form.id == null){
					  res = await this.$API.system.area.addArea.post(this.form)
				 }else {
					  res = await this.$API.system.area.updateArea.put(this.form)
				 }
				 if(res.code == 200){
					await this.refresh()
				 	this.$message.success("操作成功")
				 }else{
				 	this.$alert(res.msg, "提示", {type: 'error'})
				 }
				 this.submitLoading=false;
			}
		});
    },
	// 表单重置
    resetForm() {
      this.form = { ...this.resetData }
    },
	// 表单取消
    cancelForm() {
      this.formTitle = ""
    },
	  // 修改按钮
    async handleUpdate(item) {
      this.showParentSelect =false;
      let res = await this.$API.system.area.info.get(item.id);
      if (res.code == 200){
        Object.assign(this.form, res.data);
        this.form.level = this.form.level + "";
      }
      this.formTitle = item.name + "的修改表单"
      this.showParentSelect =false;
      this.formTitle = "编辑城市"
    },
    // 添加按钮
    async handleAdd(item) {
      this.form={}
      this.showParentSelect =false;
      this.form.pid=item.id;
      this.formTitle = item.name + "的添加表单"
    },
	// 删除按钮
    async handleDelete(item) {
		this.$confirm(`确定删除${item.name}吗?`, '提示', {
			type: 'warning'
		}).then(async () => {
	        let res = await this.$API.system.area.delArea.delete(item.id);
		    if (res.code == 200){
		    	await this.refresh();
		    	this.$message.success("删除成功")
		    }else {
			    await this.$alert(res.msg, "提示", {type: 'error'})
		    }
		}).catch(() => {

		})
	},
	// 搜索按钮
    handleInputSearch() {
      this.getAreaList()
      this.isLazy = true
    },
  }
}
</script>

<style lang="scss" scoped>
.area-page {
  height: 100%;

  .control-wrap {
    .search-wrap {
      padding: 20px;
      display: flex;
      align-items: center;

      .search-label {
        font-size: 14px;
        color: #606266;
      }
      .search-input {
        margin: 0 15px;
        width: 50%;
      }
    }

    .btn-wrap {
      margin-left: 10px;
      margin-bottom: 20px;
    }
  }
  .area-table {
    &:deep(.el-button) {
      padding: 0;
    }
  }
  .detail-form-wrap {
    .form-title {
      font-size: 16px;
      margin-bottom: 20px;
      padding-left: 20px;
    }
    height: 100%;
    padding: 20px;
    box-sizing: border-box;
    border-left: 1px solid var(--el-border-color-light);
  }
}
</style> -->
